/* 
 * Copyright 2014 ShangDao.Ltd  All rights reserved.
 * SiChuan ShangDao.Ltd PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 * 
 * @ActPublic.java  2014-9-15 上午9:45:02 - Carson
 * @author Guzhu
 * @email:muyi126@163.com
 * @version 1.0
 */

package com.android.tiango.baba.act;

import java.io.File;
import java.lang.reflect.Field;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.scsd.tiango.R;
import com.android.support.httpclient.HttpCallBack;
import com.android.support.httpclient.HttpClientAsync;
import com.android.support.httpclient.HttpParams;
import com.android.tiango.baba.BaBaseActivity;
import com.android.tiango.baba.adapter.ExpressionAdapter;
import com.android.tiango.baba.adapter.ExpressionPagerAdapter;
import com.android.tiango.baba.adapter.PhotoAdapter;
import com.android.tiango.baba.cookie.HttpUrl;
import com.android.tiango.baba.cookie.ShareCookie;
import com.android.tiango.baba.db.Draft;
import com.android.tiango.baba.db.DraftDb;
import com.android.tiango.baba.entity.BaseEntity;
import com.android.tiango.baba.util.Constants;
import com.android.tiango.baba.util.PhotosSearch;
import com.android.tiango.baba.util.SmileUtils;
import com.android.tiango.baba.util.StringUtils;
import com.android.tiango.baba.util.ToastUtils;
import com.android.tiango.baba.util.UploadMoreImageTask;
import com.android.tiango.baba.util.UploadMoreImageTask.UpLoadListener;
import com.android.tiango.baba.view.AppTitleBar;
import com.android.tiango.baba.view.MeasureGridView;
import com.j256.ormlite.dao.Dao;

/**
 * 发表帖子
 * @author YW_pc
 * 
 */
public class ActPublic extends BaBaseActivity implements OnClickListener, OnTouchListener {
	private ViewPager expressionViewpager;
	private LinearLayout expressionContainer;
	private List<String> reslist;
	private EditText mEditTextContent;
	private EditText mEditTextTittle;
	private ImageView mImageViewFace;
	private ImageView mImageViewphoto;
	private ImageView mImageViewFmt;
	private List<View> faces;
	private boolean isShowPhoto = false;
	private PhotoAdapter phototAdapter;
	private TextView mPcnumTextView;
	private String barId;
	private boolean isRequest = false;

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.layout_public);
		initView();
		initFace();
	}

	private void initView() {
		mPcnumTextView = (TextView) findViewById(R.id.tv_pcnum);
		mTitleBar = (AppTitleBar) findViewById(R.id.titlebar);
		mTitleBar.setTitle("发布话题");
		setBackOnClickListener();
		mTitleBar.setMoreText("提交");
		mTitleBar.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				checkMsg();
			}
		});
		Intent intent = getIntent();
		if (intent.hasExtra(Constants.BARID)) {
			barId = intent.getStringExtra(Constants.BARID);
		} else {
			finish();
		}
		expressionContainer = (LinearLayout) findViewById(R.id.ll_face_container);
		expressionViewpager = (ViewPager) findViewById(R.id.vPager);
		mEditTextContent = (EditText) findViewById(R.id.et_content);
		sendReply();
		mEditTextTittle = (EditText) findViewById(R.id.et_title);
		mImageViewFace = (ImageView) findViewById(R.id.iv_face);
		mImageViewphoto = (ImageView) findViewById(R.id.iv_photo);
		mImageViewFmt = (ImageView) findViewById(R.id.iv_fmt);
		mImageViewFmt.setOnClickListener(this);
		mImageViewFace.setOnClickListener(this);
		mImageViewphoto.setOnClickListener(this);
		mEditTextContent.setOnTouchListener(this);
		mEditTextTittle.setOnTouchListener(this);

		mEditTextTittle.setFocusable(true);
		mEditTextTittle.setFocusableInTouchMode(true);
		mEditTextTittle.requestFocus();
	}

	private void initFace() {
		// 表情list
		reslist = getExpressionRes(35);
		// 初始化表情viewpager
		faces = new ArrayList<View>();
		View gv1 = getGridChildView(1);
		View gv2 = getGridChildView(2);
		faces.add(gv1);
		faces.add(gv2);
		expressionViewpager.setAdapter(new ExpressionPagerAdapter(faces));
		isShowPhoto = false;
	}

	private List<String> getExpressionRes(int getSum) {
		List<String> reslist = new ArrayList<String>();
		for (int x = 1; x <= getSum; x++) {
			String filename = "ee" + x;
			reslist.add(filename);
		}
		return reslist;
	}

	/**
	 * 获取表情的gridview的子view
	 * 
	 * @param i
	 * @return
	 */
	private View getGridChildView(int i) {
		View view = View.inflate(this, R.layout.expression_gridview, null);
		MeasureGridView gv = (MeasureGridView) view.findViewById(R.id.gridview);
		List<String> list = new ArrayList<String>();
		if (i == 1) {
			List<String> list1 = reslist.subList(0, 20);
			list.addAll(list1);
		} else if (i == 2) {
			list.addAll(reslist.subList(20, reslist.size()));
		}
		list.add("delete_expression");
		final ExpressionAdapter expressionAdapter = new ExpressionAdapter(this, list);
		gv.setAdapter(expressionAdapter);
		gv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				String filename = expressionAdapter.getItem(position);
				try {
					// 文字输入框可见时，才可输入表情
					// 按住说话可见，不让输入表情
					// if (buttonSetModeKeyboard.getVisibility() != View.VISIBLE) {

					if (filename != "delete_expression") { // 不是删除键，显示表情
						// 这里用的反射，所以混淆的时候不要混淆SmileUtils这个类
						Class clz = Class.forName("com.android.tiango.baba.util.SmileUtils");
						Field field = clz.getField(filename);
						mEditTextContent.append(SmileUtils.getSmiledText(ActPublic.this,
								(String) field.get(null)));
					} else { // 删除文字或者表情
						if (!TextUtils.isEmpty(mEditTextContent.getText())) {
							mEditTextContent.requestFocus();
							int selectionStart = mEditTextContent.getSelectionStart();// 获取光标的位置
							if (selectionStart > 0) {
								String body = mEditTextContent.getText().toString();
								String tempStr = body.substring(0, selectionStart);
								int i = tempStr.lastIndexOf("[");// 获取最后一个表情的位置
								if (i != -1) {
									CharSequence cs = tempStr.substring(i, selectionStart);
									if (SmileUtils.containsKey(cs.toString()))
										mEditTextContent.getEditableText()
												.delete(i, selectionStart);
									else
										mEditTextContent.getEditableText().delete(
												selectionStart - 1, selectionStart);
								} else {
									mEditTextContent.getEditableText().delete(selectionStart - 1,
											selectionStart);
								}
							}
						}

					}
					// }
				} catch (Exception e) {
				}

			}
		});
		return view;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.iv_face:
			if (expressionContainer.getVisibility() == View.GONE) {
				expressionContainer.setVisibility(View.VISIBLE);
				choseInput();
				initFace();
			} else {
				if (isShowPhoto) {
					expressionContainer.setVisibility(View.VISIBLE);
					choseInput();
					initFace();
				} else {
					expressionContainer.setVisibility(View.GONE);
				}
			}

			break;
		case R.id.iv_photo:
			if (expressionContainer.getVisibility() == View.GONE) {
				expressionContainer.setVisibility(View.VISIBLE);
				choseInput();
				addPhoto();
			} else {
				if (isShowPhoto) {
					expressionContainer.setVisibility(View.GONE);
					isShowPhoto = false;
				} else {
					expressionContainer.setVisibility(View.VISIBLE);
					choseInput();
					addPhoto();
				}
			}
			break;
		case R.id.iv_fmt:

			break;
		default:
			break;
		}

	}

	private void addPhoto() {
		View view = LayoutInflater.from(this).inflate(R.layout.photo_selected, null);
		Gallery gl_photogl_photo = (Gallery) view.findViewById(R.id.gl_photo);

		phototAdapter = new PhotoAdapter(this, PhotosSearch.selectedDataList);
		gl_photogl_photo.setAdapter(phototAdapter);
		ArrayList<View> photos = new ArrayList<View>();
		photos.add(view);
		expressionViewpager.setAdapter(new ExpressionPagerAdapter(photos));
		isShowPhoto = true;
	}

	class DeleteAsyncTask extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... params) {
			for (int i = 0; i < PhotosSearch.selectedDataList.size(); i++) {
				String fileName = PhotosSearch.selectedDataList.get(i);
				String name = fileName.substring(fileName.lastIndexOf("\\") + 1);
				if (name.startsWith(Actlbum.MAX_TITLE_PATH)) {
					deleteFiles(name);
				}
			}
			PhotosSearch.selectedDataList.clear();
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
		}

		private boolean deleteFiles(String fName) {
			File file = new File(fName);
			return file.delete();
		}
	}

	private void clearFile() {
		new DeleteAsyncTask().execute();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		clearFile();
	}

	@Override
	protected void onStart() {
		super.onStart();
		if (null != PhotosSearch.selectedDataList && PhotosSearch.selectedDataList.size() > 0) {
			if (null != phototAdapter) {
				phototAdapter.resetAdapter(PhotosSearch.selectedDataList);
			}
		}
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		saveDraft();
	}

	private void saveDraft() {
		String title = mEditTextTittle.getText().toString();
		String content = mEditTextContent.getText().toString();
		String photo = getPic();
		Draft bean = new Draft();
		bean.setContent(content);
		bean.setTitle(title);
		bean.setPhotos(photo);

		DraftDb db = new DraftDb(this);
		try {
			Dao<Draft, Integer> dao = db.getDraftDao();
			dao.create(bean);
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

	private String getPic() {
		int size = PhotosSearch.selectedDataList.size();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < size; i++) {
			sb.append(PhotosSearch.selectedDataList.get(i));
			sb.append(";");
		}
		String photo = sb.toString();
		if (StringUtils.isEmpty(photo)) {
			return "";
		} else {
			return photo.substring(0, photo.length() - 1);
		}

	}

	private void choseInput() {
		// InputMethodManager m=(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		// m.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

		// InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		// inputMethodManager.hideSoftInputFromWindow(ActPublic.this.getCurrentFocus()
		// .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
		// // 接受软键盘输入的编辑文本或其它视图
		// inputMethodManager.showSoftInput(mEditTextContent, InputMethodManager.SHOW_FORCED);

		View view = getWindow().peekDecorView();
		if (view != null) {
			InputMethodManager inputmanger = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);
		}
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		switch (v.getId()) {
		case R.id.et_title:
			expressionContainer.setVisibility(View.GONE);
			break;
		case R.id.et_content:
			expressionContainer.setVisibility(View.GONE);
			break;

		default:
			break;
		}
		return false;
	}

	private boolean isOpen() {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		boolean isOpen = imm.isActive();
		return isOpen;
	}

	@Override
	protected void onResume() {
		int size = PhotosSearch.selectedDataList.size();
		if (size < 1) {
			mPcnumTextView.setVisibility(View.GONE);
		} else {
			mPcnumTextView.setVisibility(View.VISIBLE);
			mPcnumTextView.setText(size + "");
		}
		super.onResume();
	}

	/**
	 * 发布帖子
	 */
	private void publicData(String barId, String title, String content, String imgs) {
		showWaitingDialog();
		HttpClientAsync client = HttpClientAsync.getInstance();
		client.setPrintLog(true);
		HttpParams param = new HttpParams();
		param.put("barId", barId);
		param.put("title", title);
		param.put("content", content);
		param.put("token", ShareCookie.getToken());
		param.put("images", imgs);
		client.post(HttpUrl.getUrl(HttpUrl.ReleaseATopic), param, new HttpCallBack() {

			@Override
			public void onHttpSuccess(Object arg0) {
				dismissWaitingDialog();
				BaseEntity entity = (BaseEntity) arg0;
				if (null != entity) {
					ToastUtils.showMessage("发布成功");
					setResult(RESULT_OK);
					finish();
				}
				isRequest = false;
			}

			@Override
			public void onHttpStarted() {

			}

			@Override
			public void onHttpFailure(Exception arg0, String arg1) {
				dismissWaitingDialog();
				if (!StringUtils.isEmpty(arg1)) {
					ToastUtils.showMessage(arg1);
				}
				isRequest = false;
			}
		}, BaseEntity.class);//

	}

	private void sendReply() {
		mEditTextContent.setOnEditorActionListener(new TextView.OnEditorActionListener() {
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				checkMsg();
				return false;
			}
		});
	}

	private void upPhoto(final String title, final String msg) {
		showWaitingDialog();
		UploadMoreImageTask task = new UploadMoreImageTask();
		task.setUpLoadListener(new UpLoadListener() {

			@Override
			public void UpLoadResult(ArrayList<String> path) {
				ToastUtils.showMessage("图片上传成功");
				String imgPaths = listToString(path);
				publicData(barId, title, msg, imgPaths);
				PhotosSearch.selectedDataList.clear();
			}

			@Override
			public void UpLoadFail() {
				isRequest = false;
				dismissWaitingDialog();
				ToastUtils.showMessage("图片上传失败");
			}

			@Override
			public void UpLoadError(ArrayList<String> notUpPath) {

			}

		});
		ArrayList<String> list = PhotosSearch.selectedDataList;
		String[] array = new String[list.size()];
		task.execute(list.toArray(array));
	}

	private String listToString(ArrayList<String> list) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < list.size(); i++) {
			sb.append(list.get(i));
			sb.append(",");
		}
		String result = sb.toString();
		result = result.substring(0, result.length() - 1);
		return result;
	}

	private void checkMsg() {
		String title = mEditTextTittle.getText().toString();
		String content = mEditTextContent.getText().toString();
		if (StringUtils.isEmpty(title)) {
			ToastUtils.showMessage("请输入标题");
		} else if (title.length() < 4 || title.length() > 20) {
			ToastUtils.showMessage("标题的长度在4和20之间");
		} else if (StringUtils.isEmpty(content)) {
			ToastUtils.showMessage("请输入内容");
		} else if (content.length() < 10 || content.length() > 2000) {
			ToastUtils.showMessage("内容的长度在10和2000之间");
		} else {
			if (!isRequest) {
				isRequest = true;
				if (PhotosSearch.selectedDataList.size() < 1) {
					publicData(barId, title, content, "");
				} else {
					upPhoto(title, content);
				}
				choseInput();
				// /* 隐藏软键盘 */
				// InputMethodManager imm = (InputMethodManager) mEditTextContent.getContext()
				// .getSystemService(Context.INPUT_METHOD_SERVICE);
				// if (imm.isActive()) {
				// imm.hideSoftInputFromWindow(mEditTextContent.getApplicationWindowToken(), 0);
				// }
			}
		}
	}
}
